 package com.example.sms_listener

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**
 * 权限管理器
 * 
 * 处理Android运行时权限的申请、检查和状态管理
 * 支持SMS接收和发送权限
 */
class PermissionManager {
    
    companion object {
        private const val TAG = "PermissionManager"
        private const val SMS_PERMISSION_REQUEST_CODE = 1001
        private const val SMS_SEND_PERMISSION_REQUEST_CODE = 1002
        private const val ALL_SMS_PERMISSIONS_REQUEST_CODE = 1003
        
        /// SMS接收相关权限列表
        private val SMS_RECEIVE_PERMISSIONS = arrayOf(
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_SMS
        )
        
        /// SMS发送相关权限列表
        private val SMS_SEND_PERMISSIONS = arrayOf(
            Manifest.permission.SEND_SMS
        )
        
        /// 所有SMS权限列表
        private val ALL_SMS_PERMISSIONS = arrayOf(
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_SMS,
            Manifest.permission.SEND_SMS
        )
    }
    
    private var activity: Activity? = null
    private var permissionCallback: ((Boolean) -> Unit)? = null

    /**
     * 设置Activity引用
     */
    fun setActivity(activity: Activity?) {
        this.activity = activity
    }

    /**
     * 检查是否有所有SMS接收权限
     */
    fun hasSmsPermissions(context: Context): Boolean {
        return SMS_RECEIVE_PERMISSIONS.all { permission ->
            hasPermission(context, permission)
        }
    }

    /**
     * 检查是否有SMS发送权限
     */
    fun hasSmsSendPermission(context: Context): Boolean {
        return SMS_SEND_PERMISSIONS.all { permission ->
            hasPermission(context, permission)
        }
    }

    /**
     * 检查是否有所有SMS权限（接收和发送）
     */
    fun hasAllSmsPermissions(context: Context): Boolean {
        return ALL_SMS_PERMISSIONS.all { permission ->
            hasPermission(context, permission)
        }
    }

    /**
     * 检查单个权限
     */
    fun hasPermission(context: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
    }

    /**
     * 请求SMS接收权限
     */
    fun requestSmsPermissions(activity: Activity, callback: (Boolean) -> Unit) {
        this.permissionCallback = callback
        
        // 检查是否已有权限
        if (hasSmsPermissions(activity)) {
            callback(true)
            return
        }
        
        // 检查是否需要显示权限说明
        val shouldShowRationale = SMS_RECEIVE_PERMISSIONS.any { permission ->
            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
        }
        
        if (shouldShowRationale) {
            Log.d(TAG, "需要向用户解释SMS接收权限用途")
        }
        
        // 请求权限
        ActivityCompat.requestPermissions(
            activity,
            SMS_RECEIVE_PERMISSIONS,
            SMS_PERMISSION_REQUEST_CODE
        )
    }

    /**
     * 请求SMS发送权限
     */
    fun requestSmsSendPermission(activity: Activity, callback: (Boolean) -> Unit) {
        this.permissionCallback = callback
        
        // 检查是否已有权限
        if (hasSmsSendPermission(activity)) {
            callback(true)
            return
        }
        
        // 检查是否需要显示权限说明
        val shouldShowRationale = SMS_SEND_PERMISSIONS.any { permission ->
            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
        }
        
        if (shouldShowRationale) {
            Log.d(TAG, "需要向用户解释SMS发送权限用途")
        }
        
        // 请求权限
        ActivityCompat.requestPermissions(
            activity,
            SMS_SEND_PERMISSIONS,
            SMS_SEND_PERMISSION_REQUEST_CODE
        )
    }

    /**
     * 请求所有SMS权限（接收和发送）
     */
    fun requestAllSmsPermissions(activity: Activity, callback: (Boolean) -> Unit) {
        this.permissionCallback = callback
        
        // 检查是否已有权限
        if (hasAllSmsPermissions(activity)) {
            callback(true)
            return
        }
        
        // 检查是否需要显示权限说明
        val shouldShowRationale = ALL_SMS_PERMISSIONS.any { permission ->
            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
        }
        
        if (shouldShowRationale) {
            Log.d(TAG, "需要向用户解释所有SMS权限用途")
        }
        
        // 请求权限
        ActivityCompat.requestPermissions(
            activity,
            ALL_SMS_PERMISSIONS,
            ALL_SMS_PERMISSIONS_REQUEST_CODE
        )
    }

    /**
     * 请求单个权限
     */
    fun requestPermission(activity: Activity, permission: String, callback: (Boolean) -> Unit) {
        this.permissionCallback = callback
        
        if (hasPermission(activity, permission)) {
            callback(true)
            return
        }
        
        ActivityCompat.requestPermissions(
            activity,
            arrayOf(permission),
            SMS_PERMISSION_REQUEST_CODE
        )
    }

    /**
     * 处理权限请求结果
     * 
     * 应该在Activity的onRequestPermissionsResult中调用此方法
     */
    fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            SMS_PERMISSION_REQUEST_CODE -> {
                val allGranted = grantResults.isNotEmpty() && 
                    grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                Log.d(TAG, "SMS接收权限请求结果: $allGranted")
                permissionCallback?.invoke(allGranted)
                permissionCallback = null
            }
            SMS_SEND_PERMISSION_REQUEST_CODE -> {
                val allGranted = grantResults.isNotEmpty() && 
                    grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                Log.d(TAG, "SMS发送权限请求结果: $allGranted")
                permissionCallback?.invoke(allGranted)
                permissionCallback = null
            }
            ALL_SMS_PERMISSIONS_REQUEST_CODE -> {
                val allGranted = grantResults.isNotEmpty() && 
                    grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                Log.d(TAG, "所有SMS权限请求结果: $allGranted")
                permissionCallback?.invoke(allGranted)
                permissionCallback = null
            }
        }
    }

    /**
     * 检查权限是否被永久拒绝
     */
    fun isPermissionPermanentlyDenied(activity: Activity, permission: String): Boolean {
        return !hasPermission(activity, permission) &&
            !ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
    }

    /**
     * 获取权限状态 (Activity版本)
     * 
     * 返回值：
     * 0 = 已授予
     * 1 = 被拒绝
     * 2 = 被永久拒绝
     * 3 = 未知
     */
    fun getPermissionStatus(activity: Activity, permission: String): Int {
        return when {
            hasPermission(activity, permission) -> 0 // 已授予
            isPermissionPermanentlyDenied(activity, permission) -> 2 // 被永久拒绝
            else -> 1 // 被拒绝
        }
    }

    /**
     * 获取权限状态 (Context版本)
     * 
     * 返回值：
     * 0 = 已授予
     * 1 = 被拒绝
     * 3 = 未知
     */
    fun getPermissionStatus(context: Context, permission: String): Int {
        return when {
            hasPermission(context, permission) -> 0 // 已授予
            else -> 1 // 被拒绝
        }
    }

    /**
     * 获取所有SMS权限的状态
     */
    fun getSmsPermissionsStatus(activity: Activity): Map<String, Int> {
        return SMS_RECEIVE_PERMISSIONS.associateWith { permission ->
            getPermissionStatus(activity, permission)
        }
    }

    /**
     * 检查设备是否支持运行时权限
     */
    fun isRuntimePermissionSupported(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    }

    /**
     * 获取被拒绝的权限列表
     */
    fun getDeniedPermissions(context: Context): List<String> {
        return SMS_RECEIVE_PERMISSIONS.filter { permission ->
            !hasPermission(context, permission)
        }
    }

    /**
     * 获取被永久拒绝的权限列表
     */
    fun getPermanentlyDeniedPermissions(activity: Activity): List<String> {
        return SMS_RECEIVE_PERMISSIONS.filter { permission ->
            isPermissionPermanentlyDenied(activity, permission)
        }
    }

    /**
     * 打开应用设置页面
     */
    fun openAppSettings(activity: Activity) {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = Uri.parse("package:${activity.packageName}")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            activity.startActivity(intent)
        } catch (e: Exception) {
            Log.e(TAG, "打开应用设置失败", e)
            // 如果无法打开应用设置，尝试打开系统设置
            try {
                val intent = Intent(Settings.ACTION_SETTINGS)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                activity.startActivity(intent)
            } catch (e2: Exception) {
                Log.e(TAG, "打开系统设置失败", e2)
            }
        }
    }

    /**
     * 清理资源
     */
    fun cleanup() {
        activity = null
        permissionCallback = null
    }
}